// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package info

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib"
)

// Logic
// 场次详情.
type Logic struct {
	arcade   *models.Arcades
	admin    *models.ArcadeAdmins
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err     error
		has     bool
		pond    *models.ArcadePond
		res     = result.New()
		session *models.TicketSession
		ticket  *models.Ticket
	)

	// 1. 查询场次
	if session, has, err = services.NewTicketSessionService().Dao.GetById(ctx, o.request.Id); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 校验场次.
	if !has || session.Deleted.IsYes() || session.ArcadeId != o.arcade.Id {
		return res.WithError(errs.ErrTicketSessionNotFound)
	} else {
		o.response.With(session)
	}

	// 3. 查询渔票.
	if ticket, has, err = services.NewTicketService().Dao.GetById(ctx, session.TicketId); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 4. 校验渔票.
	if !has || ticket.ArcadeId != o.arcade.Id {
		return res.WithError(errs.ErrTicketNotFound)
	} else {
		o.response.WithTicket(ticket)
	}

	// 5. 鱼塘信息.
	if pond, has, err = services.NewArcadePondService().Dao.GetById(ctx, ticket.PondId); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 6. 校验鱼塘
	if !has || pond.ArcadeId != o.arcade.Id {
		return res.WithError(errs.ErrArcadePondNotFound)
	} else {
		o.response.Ticket.WithPond(pond)
	}

	// 7. 处理完成.
	return res.With(o.response)
}
